package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig(maxFileSize=5*1024*1024)
public class UploadServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		
		// 1. 表单中的普通内容
		String name = req.getParameter("name");
		System.out.println(name);
		
		// 2. 表单中的文件
		Part part = req.getPart("pic");
//		System.out.println(part);
		
		String fileName = part.getHeader("Content-Disposition");
		System.out.println(fileName);
		fileName = fileName.substring(fileName.indexOf("filename=\"")+"filename=\"".length());
		fileName = fileName.substring(0,fileName.length()-1);
		System.out.println(fileName);
		
		// .png .jpg
		
		// 防止重复，该以下文件名
		UUID uuid = UUID.randomUUID();
		String newFileName = uuid.toString()+fileName.substring(fileName.length()-4);
		
		
		// 保存文件
		ServletContext sc = getServletContext();
		String filePath = sc.getRealPath("/upload/")+newFileName;
		part.write(filePath);
		
		pw.print(name+"<br/>"+"上传成功");
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
